<?php
/**
 * Created by PhpStorm.
 * User: cephei
 * Date: 11/29/15
 * Time: 8:11 PM
 */

namespace Plugins\BTDRadar;

use Core\PluginContainer;

class Plugin_BTDRadar{
    public function search($keyWord){
        $curl = PluginContainer::getInstance()->make('curl');
        $curl->timeOut=60;
        $response = $curl->sendRequest("https://btdigg.org/search?q=$keyWord&order=0");
        preg_match_all('/href="(magnet\:\?xt=urn\:btih\:.+?)"/',$response,$magnetList);
        preg_match_all('/attr_val">(.*?[G|M|K]B)<\/span>/',$response,$sizeList);
        preg_match_all('/<a href="\/search\?info_hash=(.*?)">(.*?)<\/a>/',$response,$nameList);
        $result=[];
        for($i=0;$i<count($magnetList[1]);$i++){
            $result[] = [
                "url"=>$magnetList[1][$i],
                "name"=>$nameList[2][$i],
                "size"=>$this->convertSize($sizeList[1][$i])
            ];
        }
        return $result;
    }
    public function convertSize($origin){
        $sizeArray = explode('&nbsp;',$origin);
        $unitSize=1;
        switch($sizeArray[1]){
            case "GB":
                $unitSize = 1024*1024*1024;
                break;
            case "MB":
                $unitSize = 1024*1024;
                break;
            case "KB":
                $unitSize = 1024;
                break;
        }
        return ((float)$sizeArray[0])*$unitSize;
    }
}